package org.spolo.android.support.tween;

import java.util.ArrayList;

import org.spolo.android.support.nodetree.StageView;

public class InterpolateManager {
	private static InterpolateManager interpolateManager;
	private StageView stageView;
	private ArrayList<InterpolateBase> interpolate_list;
	private ArrayList<InterpolateBase> addbuffer;;
	private ArrayList<InterpolateBase> delbuffer;

	private InterpolateManager() {
		interpolate_list = new ArrayList<InterpolateBase>();
		addbuffer = new ArrayList<InterpolateBase>();
		delbuffer = new ArrayList<InterpolateBase>();
	}

	public static InterpolateManager getInstance() {
		if (interpolateManager == null) {
			interpolateManager = new InterpolateManager();
		}
		return interpolateManager;
	}

	public void AddInterpolate(InterpolateBase interpolate) {
		addbuffer.add(interpolate);
		if (this.stageView != null) {
			this.stageView.postInvalidate();
		}
	}

	public void OnTick(long tick) {
		ArrayList<InterpolateBase> list = refreshList();
		for (InterpolateBase item : list) {
			if (item.isFinish) {
				delbuffer.add(item);
				continue;
			} else {
				item.stepIt(tick);
			}
		}
	}

	/**
	 * 刷新差值器列表,删除已经执行完的,添加上新加入的 并将缓冲中的内容清空
	 */
	public ArrayList<InterpolateBase> refreshList() {
		for (InterpolateBase del : delbuffer) {
			interpolate_list.remove(del);
		}
		for (InterpolateBase add : addbuffer) {
			interpolate_list.add(add);
		}
		delbuffer.clear();
		addbuffer.clear();
		return interpolate_list;
	}

	public boolean isEmpty() {
		return interpolate_list.size() == 0;
	}

	public void setView(StageView view) {
		this.stageView = view;
	}
}
